package com.niuwa.p2p.service.impl.protocol;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.utils.DictConstant;
import com.niuwa.p2p.dao.protocol.ProtocolAuditDao;
import com.niuwa.p2p.dao.protocol.ProtocolDao;
import com.niuwa.p2p.service.protocol.IProtocolAuditService;
import com.niuwa.p2p.vo.protocol.ProductProtocolVo;
import com.niuwa.p2p.vo.protocol.ProtocolAuditVo;

/**
 * 协议接口
 * @author lijian
 */
@Service
public class ProtocolAuditServiceImpl implements IProtocolAuditService {

	@Autowired
	private ProtocolAuditDao protocolAuditDao;
	
	@Autowired
	private ProtocolDao protocolDao;

	@Override
	public JsonResult selectProtocolAuditInfoBySelective(ProtocolAuditVo protocolAuditVo) {
		JsonResult result = new JsonResult(false,"无审批信息！");
		try {
			if (Long.valueOf(protocolAuditVo.getProtId())!=null) {
				Map<String, Object> paramMap=new HashMap<String, Object>();
				paramMap.put("protId", protocolAuditVo.getProtId());
				paramMap.put("operateType", DictConstant.OperateType.REJECT.getCode());
				ProtocolAuditVo auditVo=protocolAuditDao.selectProtocolAuditInfoBySelective(paramMap);
				if (auditVo!=null) result = new JsonResult(true,auditVo);
			}else{
				result = new JsonResult(false,"参数有误！");
			}
		} catch (Exception e) {
			//TODO LOG
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public JsonResult protocolAudit(ProtocolAuditVo protocolAuditVo) {
		JsonResult jsonResult=new JsonResult(false,"操作异常!");
		try {
			//先判断当前操作协议是否存在
			ProductProtocolVo protocol=protocolDao.getProtocolByProtId(protocolAuditVo.getProtId());
			if (protocol!=null &&
					protocol.getDelFlag().equals(DictConstant.FlagStatus.N.toString())) {
				String protStatus=DictConstant.ProtStatus.NO_PASS.getCode();//默认未通过
				if (protocolAuditVo.getOperateType().equals(DictConstant.OperateType.PASS.getCode())) {//拒绝操作
					protStatus=DictConstant.ProtStatus.PASS.getCode();
				}
				Map<String, Object> paramMap =new HashMap<String, Object>();
				paramMap.put("protStatus", protStatus);
				paramMap.put("protId", protocolAuditVo.getProtId());
				Object obj = protocolDao.updateProtoStatusBySelective(paramMap);
				Object result=protocolAuditDao.protocolAudit(protocolAuditVo);
				if ((Integer.parseInt(obj.toString())+
						Integer.parseInt(result.toString()))>1) {
					if (Integer.parseInt(obj.toString())>0) {
						jsonResult=new JsonResult(true,"操作成功!");
					}
				}else{
					jsonResult=new JsonResult(false,"操作失败!");
				}
			}else{
				jsonResult=new JsonResult(false,"操作的信息不存在，请刷新重试!");
			}
		} catch (Exception e) {
			// TODO: LOG
			e.printStackTrace();
		}
		return jsonResult;
	}

}
